package dataStructrue.squence.LinkList;

public class LinkList<T> {
    // 头节点
    private Node<T> head;
    // 链表长度
    private int length;
    // 初始化
    public LinkList() {
        this.head = new Node<>(null,null);
        this.length = 0;
    }
    public void add(T data) {
        Node temp = head;
        while (temp.next!=null) {
            temp = temp.next;
        }
        Node newNode = new Node(data,null);
        temp.next = newNode;
        this.length++;
    }
    public void insert(T data,int index) {
        Node temp = head;
        for (int i = 0; i < index; i++) {
            if (temp.next==null) {
                break;
            }
            temp = temp.next;
        }
        Node newNode = new Node(data,temp.next);
        temp.next = newNode;
        this.length++;
    }
    public void display() {
        Node temp = head;
        while (temp.next!=null) {
            temp = temp.next;
            System.out.print(temp.item+" ");

        }
        System.out.print('\n');
    }
    public Node remove(int index) {
        Node temp = head;
        for (int i = 0; i < index; i++) {
            if (temp.next==null) {
                break;
            }
            temp = temp.next;
        }
        Node removed = temp.next;
        temp.next = temp.next.next;
        this.length --;
        return removed;
    }
    public void reverse() {
        reverse(this.head.next);
    }
    // 链表反转
    public Node reverse(Node curr) {
        if (curr.next==null) {
            head.next = curr;
            return curr;
        }
        Node pre = reverse(curr.next);
        pre.next = curr;
        curr.next = null;

        return curr;
    }
    public static void main(String[] args) {
        LinkList<Integer> linkList = new LinkList<>();
        Node temp = linkList.head;
        for (int i = 0; i < 10; i++) {
            linkList.add(i+1);
        }
        linkList.display();
        linkList.add(100);
        linkList.insert(99,3);
        System.out.println(linkList.remove(3).item);
        System.out.println(linkList.length);
        linkList.reverse();
        linkList.display();
    }

}
